﻿using Manon.Admin.Web.ApplicationCore.Interfaces;
using Manon.Admin.Web.Models;
using Manon.Core.IOC;
using Manon.Core.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

namespace Manon.Admin.Web.Controllers
{

    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly IRoleService _roleService;
        public HomeController(ILogger<HomeController> logger, IRoleService roleService)
        {
            _logger = logger;
            _roleService = roleService;
        }
        
        public IActionResult Index()
        {
            return View();
        }

        [Authorize]
        [HttpGet]
        public async Task<List<Menu>> GetMenu()
        {
            string filePath = Directory.GetCurrentDirectory().Replace("\\", "/");

            List<Menu> menus = JsonHelper.Read<List<Menu>>($@"{filePath}/Config/menu.json");

            if (menus == null) return null;
             
            //过滤权限
            List<string> listIds = await _roleService.GetUserMenuIds();
            List<Menu> newMenus = new List<Menu>();
            foreach (var item in menus)
            {
                if (!listIds.Contains(item.id)) continue;
                List<Menu> newMenusChild = new List<Menu>();
                foreach (var child in item.children)
                {
                    if (!listIds.Contains(child.id)) continue;
                    child.children = null;
                    newMenusChild.Add(child);
                }
                item.children = newMenusChild;
                newMenus.Add(item);
            }

            return newMenus;
        }

        


    }
}
